import DataStoredInToken from "../interface/DataStoredInToken.if";
import jwt from "jsonwebtoken";
import AuthenticationMissingException from "../exception/authenticationMissing.ex";
import { Handler, Response, NextFunction } from "express";
import userModel from "../controller/user/user.model";
import WrongAuthInfoException from "../exception/wrongAuthInfo.ex";
import RequestWithUser from "interface/requestWithUserId.if";

/**
 *
 * @param err 错误信息
 * 注意这是一个匿名函数
 * 检查 客户端发送来的 cookies中的 Authorization 头 里的token 是否有效
 */
async function authMiddleware(
  req: RequestWithUser,
  res: Response,
  next: NextFunction
) {
  const cookies = req.cookies;
  // Authorization 是发放token的时候 使用的 头信息
  const key = process.env.JWT_SECRET;

  if (cookies && cookies.Authorization) {
    try {
      const verifyResult = jwt.verify(
        cookies.Authorization,
        key
      ) as DataStoredInToken;

      const userId = verifyResult._id;

      const user = await userModel.findById(userId);

      if (user) {
        // 如果token有效,就从数据库中获取该user的 _id并传递给下一个路由使用
        req._userId = userId;
        next();
        return;
      } else {
        next(new WrongAuthInfoException());
      }
    } catch (error) {
      next(new WrongAuthInfoException());
    }
  } else {
    next(new AuthenticationMissingException());
  }
}

export default authMiddleware;
